import base64
import logging
import time
import uuid
from datetime import datetime

from ajson import aj
from django.core.cache import cache
from django.db.models import Q, Sum
from rest_framework.decorators import api_view
import requests
from rest_framework.views import APIView

from apps.baseData.models import User, ScoreDetails
from apps.help.models import ReportTempImage
from apps.help.serializers import ReportTempImageSerializer
from config import Aliyun, OutTime
from utils import AliyunUtil
from utils.network import Result, AMap

logger = logging.getLogger(__name__)


@api_view(['GET', 'OPTIONS'])
def ipToAddress(request, ip):
    result = AMap.regeo(ip)
    addressComponent = result['regeocode']['addressComponent']

    if 'original' in request.GET.keys() and request.GET.get('original'):
        return Result.success(data=result)

    return Result.success(data=result,
                          address="{}{}{}{}{}"
                          .format(addressComponent['city'],
                                  addressComponent['district'],
                                  addressComponent['township'],
                                  addressComponent['streetNumber']['street'],
                                  addressComponent['streetNumber']['number'],
                                  ))


class ReportView(APIView):
    def post(self, request):
        logger.info("上传举报图片")
        report_img = request.FILES.get('file')
        suffix = str(report_img.name).split('.')
        # 加上后缀
        filename = str(uuid.uuid4()) + '.' + suffix[len(suffix) - 1]
        _file = report_img.file
        file_base = b''
        bt = _file.read()
        while bt:
            file_base += bt
            bt = _file.read()
        # byte转base64
        base64_str = base64.b64encode(file_base).decode('utf-8')
        img_base64 = 'data:image/jpg;base64,' + base64_str
        # 上传文件
        try:
            response = AliyunUtil.upload_img(bucket_name=Aliyun.BUCKET, filename=Aliyun.Report_Path + filename,
                                             base64=_file)
        except Exception as e:
            logger.error(str(e))
            return Result.error(response=str(e))
        # 设置redis缓存一个月删除
        redis_data = {
            'bucket': Aliyun.BUCKET,
            'filename': filename,
            'base64': img_base64,
            'aliyun_request_id': response.request_id
        }
        out_time = time.time() + OutTime.REPORT_IMG_OUT_TIME
        cache.set('report_' + str(out_time))
        url = Aliyun.get_img_path(Aliyun.Report_Path + filename)
        temp = ReportTempImage(filename=filename,
                               url=url,
                               bucket=Aliyun.BUCKET,
                               request_id=response.request_id,
                               out_time=out_time)
        temp.save()
        serializer = ReportTempImageSerializer(temp)
        return Result.success(data=url, temp=serializer.data)


class SelectUserScoreDetails(APIView):
    def get(self, request):
        user_id = request.GET.get('userId')
        user = User.objects.get(pk=user_id)
        # 减的分数
        sub_score = ScoreDetails.objects.filter(user=user, status=False).aggregate(sum=Sum('score'))
        add_score = ScoreDetails.objects.filter(user=user, status=True).aggregate(sum=Sum('score'))
        sub_score['sum'] = int(sub_score['sum']) if sub_score['sum'] is not None else 0
        add_score['sum'] = int(add_score['sum']) if add_score['sum'] is not None else 0
        return Result.success(data={
            'score': 80 + add_score['sum'] - sub_score['sum'],
            'userId': user_id,
            'sub_score': sub_score['sum'] if sub_score['sum'] is not None else 0,
            'add_score': add_score['sum'] if add_score['sum'] is not None else 0,
        })
